package org.lq.er.view.student_info;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.lq.er.entity.Student;
import org.lq.er.service.StudentService;
import org.lq.er.service.impl.StudentServiceImpl;

import javax.swing.JScrollPane;
import javax.swing.JPopupMenu;
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JMenu;
import javax.swing.JButton;
import javax.swing.JFileChooser;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextPane;
import javax.swing.BoxLayout;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.DropMode;
/**
 * 学生信息主视图
 * @author 宋铀
 * 
 * @package org.lq.er.view.student_info
 * @date 2020年8月24日下午8:14:10
 */
public class ER_student_main extends JFrame {

	private JPanel contentPane;
	private JScrollPane scrollPane;
	private static JTable table;
	private JPanel panel_op;
	private JTextField text_search;
	private JPanel panel_ps;
	private JTextPane textPane;
	private JPopupMenu popupMenu;
	private JMenuItem mntm_add;
	private JMenuItem mntm_update;
	private JMenuItem mntm_del;
	private StudentService studentService = new StudentServiceImpl();
	
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ER_student_main frame = new ER_student_main();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public ER_student_main() {
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 666, 481);
		setLocationRelativeTo(null);
		contentPane = new JPanel();
		contentPane.setBackground(Color.white);
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		
		scrollPane = new JScrollPane();
		contentPane.add(scrollPane, BorderLayout.CENTER);
		
		table = new JTable();
		table.setModel(new DefaultTableModel(
			new Object[][] {
			},
			new String[] {
				"\u8EAB\u4EFD\u8BC1\u53F7\u7801", "\u59D3\u540D", "\u5BC6\u7801", "\u624B\u673A\u53F7\u7801", "\u73ED\u7EA7", "\u5B66\u53F7"
			}
		));
		scrollPane.setViewportView(table);
		
		popupMenu = new JPopupMenu();
		addPopup(table, popupMenu);
		
		mntm_add = new JMenuItem("添加");
		mntm_add.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				ER_student_add add = new ER_student_add();
				add.setBounds(ER_student_main.this.getX()+100, ER_student_main.this.getY(), add.getWidth(), add.getHeight());
				add.setVisible(true);
				
				// 监听窗体是否被关闭
				add.addWindowListener(new WindowAdapter() {
					@Override
					public void windowClosed(WindowEvent e) {
						//当添加窗体关闭的时候,调用表格初始化方法
						initTable();
					}
					@Override
					public void windowClosing(WindowEvent e) {
					}
				});
			}
		});
		popupMenu.add(mntm_add);
		
		mntm_update = new JMenuItem("修改");
		mntm_update.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// 点击修改事件
				Student student = new Student();
				// 获取点击的行数
				int rowIndex = table.getSelectedRow();
				// 获取点击行的各列的值
				String cardId = table.getValueAt(rowIndex, 0).toString();
				String name = table.getValueAt(rowIndex, 1).toString();
				String passwd = table.getValueAt(rowIndex, 2).toString();
				String phone_no = table.getValueAt(rowIndex, 3).toString();
				String classes = table.getValueAt(rowIndex, 4).toString();
				int stu_no = Integer.parseInt(table.getValueAt(rowIndex, 5).toString());
				// 学生类赋值
				student.setCard_id(cardId);
				student.setName(name);
				student.setPassword(passwd);
				student.setPhone_no(phone_no);
				student.setClasses(classes);
				student.setStu_no(stu_no);
				ER_student_update update = new ER_student_update(student);
				update.setBounds(ER_student_main.this.getX()+100, ER_student_main.this.getY(), update.getWidth(), update.getHeight());
				update.setVisible(true);
				
				// 监听窗体是否被关闭
				update.addWindowListener(new WindowAdapter() {
					@Override
					public void windowClosed(WindowEvent e) {
						//当添加窗体关闭的时候,调用表格初始化方法
						initTable();
					}
					@Override
					public void windowClosing(WindowEvent e) {
					}
				});
			}
		});
		popupMenu.add(mntm_update);
		
		mntm_del = new JMenuItem("删除");
		mntm_del.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// 点击删除事件
				// 获取当前点击的行
				int rowIndex = table.getSelectedRow();
				String cardId = table.getValueAt(rowIndex, 0).toString();
				// 询问是否删除
				int num = JOptionPane.showConfirmDialog(ER_student_main.this, "是否删除?", "提示", JOptionPane.INFORMATION_MESSAGE);
				if (num == 0) {
					// 删除操作
					if (studentService.deleteByCard_id(cardId)) {
						JOptionPane.showMessageDialog(ER_student_main.this, "删除成功!", "提示", JOptionPane.INFORMATION_MESSAGE);
						initTable();
					} else {
						JOptionPane.showMessageDialog(ER_student_main.this, "删除失败!", "错误", JOptionPane.ERROR_MESSAGE);
					}
				}
				// 初始化表格
				initTable();
			}
		});
		popupMenu.add(mntm_del);
		
		panel_op = new JPanel();
		contentPane.add(panel_op, BorderLayout.NORTH);
		
		JButton btn_download = new JButton("下载学生信息");
		btn_download.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// 调用方法导出学生
				exportExcel();
			}
		});
		
		JButton btn_search = new JButton("搜索");
		btn_search.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// 获取搜索内容
				String item = text_search.getText();
				List<Student> list = studentService.getByItem(item);
				initTable(list);
				text_search.setText("");
			}
		});
		
		text_search = new JTextField();
		text_search.setColumns(10);
		
		JLabel lbl_search = new JLabel("身份证号码/姓名/手机号/班级:");
		
		JButton btnNewButton = new JButton("显示全部");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				List<Student> list = studentService.findAll();
				initTable(list);
			}
		});
		GroupLayout gl_panel_op = new GroupLayout(panel_op);
		gl_panel_op.setHorizontalGroup(
			gl_panel_op.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_panel_op.createSequentialGroup()
					.addGap(35)
					.addComponent(btn_download)
					.addPreferredGap(ComponentPlacement.RELATED, 61, Short.MAX_VALUE)
					.addComponent(btnNewButton)
					.addGap(18)
					.addComponent(lbl_search)
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addComponent(text_search, GroupLayout.PREFERRED_SIZE, 74, GroupLayout.PREFERRED_SIZE)
					.addGap(18)
					.addComponent(btn_search, GroupLayout.PREFERRED_SIZE, 90, GroupLayout.PREFERRED_SIZE)
					.addContainerGap())
		);
		gl_panel_op.setVerticalGroup(
			gl_panel_op.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_panel_op.createSequentialGroup()
					.addGroup(gl_panel_op.createParallelGroup(Alignment.BASELINE)
						.addComponent(text_search, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(btn_search, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
						.addComponent(lbl_search)
						.addComponent(btn_download, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
						.addComponent(btnNewButton))
					.addContainerGap())
		);
		panel_op.setLayout(gl_panel_op);
		
		panel_ps = new JPanel();
		contentPane.add(panel_ps, BorderLayout.SOUTH);
		
		textPane = new JTextPane();
		textPane.setEditable(false);
		textPane.setEnabled(false);
		textPane.setText("注:右击可进增加,删除,修改");
		GroupLayout gl_panel_ps = new GroupLayout(panel_ps);
		gl_panel_ps.setHorizontalGroup(
			gl_panel_ps.createParallelGroup(Alignment.LEADING)
				.addGroup(Alignment.TRAILING, gl_panel_ps.createSequentialGroup()
					.addContainerGap(462, Short.MAX_VALUE)
					.addComponent(textPane, GroupLayout.PREFERRED_SIZE, 168, GroupLayout.PREFERRED_SIZE)
					.addContainerGap())
		);
		gl_panel_ps.setVerticalGroup(
			gl_panel_ps.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_ps.createSequentialGroup()
					.addComponent(textPane, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
					.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
		);
		panel_ps.setLayout(gl_panel_ps);
		
		// 初始化table中的数值
		initTable();
	}
	/**
	 * 生成右键菜单操作的方法
	 * @param component
	 * @param popup
	 */
	private static void addPopup(Component component, final JPopupMenu popup) {
		component.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				if (e.isPopupTrigger()) {
					showMenu(e);
				}
			}
			public void mouseReleased(MouseEvent e) {
				if (e.isPopupTrigger()) {
					showMenu(e);
				}
			}
			private void showMenu(MouseEvent e) {
				int index = table.rowAtPoint(e.getPoint());
				table.setRowSelectionInterval(index, index);
				popup.show(e.getComponent(), e.getX() + 10, e.getY());
				
			}
		});
	}
	
	
	/**
	 * 初始化表格
	 */
	public void initTable() {
		initTable(studentService.findAll());
	}
	public void initTable(List<Student> list) {
		DefaultTableModel dtm = (DefaultTableModel) table.getModel();
		int count = dtm.getRowCount(); //获取当前表的行
		// 清空表格
		for (int i = 0; i < count; i++) {
			dtm.removeRow(0);
		}
		// 添加表格数据
		for (Student student : list) {
			dtm.addRow(new Object[] {
				student.getCard_id(),
				student.getName(),
				student.getPassword(),
				student.getPhone_no(),
				student.getClasses(),
				student.getStu_no()
			});
		}
	}
	
	/**
	 * 导出学生信息
	 */
	public void exportExcel() {
		// 创建工作簿对象 
		HSSFWorkbook workbook = new HSSFWorkbook();
		// 创建工作表对象
		HSSFSheet sheet = workbook.createSheet();
		workbook.setSheetName(0, "学生信息");
		// 创建工作标的行
		HSSFRow row = sheet.createRow(0);// 设置第一行
		HSSFCell cell = row.createCell(0);
		cell.setCellValue("身份证号码");
		row.createCell(1).setCellValue("姓名");
		row.createCell(2).setCellValue("手机号");
		row.createCell(3).setCellValue("班级");
		row.createCell(4).setCellValue("学号");
		List<Student> list = studentService.findAll();
		for (int i = 0; i < list.size(); i++) {
			Student s = list.get(i);
			HSSFRow row2 = sheet.createRow(i+1);
			row2.createCell(0).setCellValue(s.getCard_id());
			row2.createCell(1).setCellValue(s.getName());
			row2.createCell(2).setCellValue(s.getPhone_no());
			row2.createCell(3).setCellValue(s.getClasses());
			row2.createCell(4).setCellValue(s.getStu_no());
		}		
		String fileName = "学生数据"+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+".xls";
		// 创建JFileChooser
		JFileChooser jf = new JFileChooser();
		jf.setSelectedFile(new File(fileName));
		int result = jf.showSaveDialog(null);
		File path = jf.getSelectedFile();
		try {
			if (result == 0) {
				workbook.write(new File(path+fileName));
			} else {
				workbook.write(new File("C:\\Users\\Administrator\\Desktop\\"+fileName));
			}
			JOptionPane.showMessageDialog(ER_student_main.this, "学生信息下载成功!", "提示", JOptionPane.INFORMATION_MESSAGE);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
